/*
* ============================================================================
* 功能描述 ：温湿度
* 作者       ：ggls
* 创建日期 ：2024.04.24
* ----------------------------------------------------------------------------
* 更新历史 ：
*	日期 　　- 修改者   : 更新内容描述
*
* ============================================================================
*/

#include "main.h"

#define SHT40_ADDRESS 0x44

float SHT40_GetTemperature(void)
{
    unsigned char txBuffer[2];
    unsigned char rxBuffer[6];

    txBuffer[0] = 0x24;
    txBuffer[1] = 0x00;

    TEMP_I2C_Start();
    TEMP_write_byte(SHT40_ADDRESS << 1);
   	TEMP_read_ACK();
    TEMP_write_byte(txBuffer[0]);
    TEMP_read_ACK();
    TEMP_write_byte(txBuffer[1]);
    TEMP_read_ACK();
    TEMP_I2C_Stop();

    DelayXms(10);

    TEMP_I2C_Start();
    TEMP_write_byte(SHT40_ADDRESS << 1 | 0x01);
    TEMP_read_ACK();
    for(int i = 0; i < 5; i++)
    {
        rxBuffer[i] = TEMP_read_byte();
        I2C_Ack();
    }
    rxBuffer[5] = TEMP_read_byte();
    I2C_NAck();
    I2C_Stop();

    unsigned short int rawTemp = (rxBuffer[0] << 8) | rxBuffer[1];
    float temp = -45 + 175 * ((float)rawTemp / (float)0xFFFF);

    return temp;
}

float SHT40_GetHumidity(void)
{
    unsigned char txBuffer[2];
    unsigned char rxBuffer[6];

    txBuffer[0] = 0x24;
    txBuffer[1] = 0x00;

    TEMP_I2C_Start();
    TEMP_write_byte(SHT40_ADDRESS << 1);
    TEMP_read_ACK();
    TEMP_write_byte(txBuffer[0]);
    TEMP_read_ACK();
    TEMP_write_byte(txBuffer[1]);
    TEMP_read_ACK();
    TEMP_I2C_Stop();

    DelayXms(10);

    TEMP_I2C_Start();
    TEMP_write_byte(SHT40_ADDRESS << 1 | 0x01);
   
    TEMP_read_ACK();
    for(int i = 0; i < 5; i++)
    {
        rxBuffer[i] = TEMP_read_byte();
        TEMP_read_ACK();
    }
    rxBuffer[5] = TEMP_read_byte();
    I2C_NAck();
    I2C_Stop();

    unsigned short int rawHumidity = (rxBuffer[3] << 8) | rxBuffer[4];
    float humidity = 100 * ((float)rawHumidity / (float)0xFFFF);

    return humidity;
}
